package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

//手写缓存工具类
@Component
public class CacheClient {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //普通缓存
    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    //逻辑过期缓存
    public void setWithLogicalExpire(String key, Object value, Long logicalExpare, TimeUnit unit){
        //1.封装成redisData
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(logicalExpare)));
        //2.缓存到redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    //普通查询缓存
    public <R, ID> R queryWithPassThroucgh(String keyPrefix, ID id, Long time, TimeUnit unit, Class<R> type, Function<ID, R> dbFallback) {
        //1.根据id从redis中查询缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        // 2.如果为空字符串，则返回错误信息（缓存穿透）
        if ("".equals(json)) {
            return null;
        }

        //3.如过存在则直接返回商铺信息
        if (StrUtil.isNotBlank(json)) {
            R result = JSONUtil.toBean(json, type);
            return result;
        }

        //4.不存在则查询数据库,这里使用函数式编程
        //因为这个方法只有调用者才能运行（不知道查哪个数据库）
        R result = dbFallback.apply(id);

        //5.若数据库中不存在则直接返回错误
        if (result == null) {
            // 6.将空值写入redis中（应对缓存穿透）
            set(key, "", time, unit);
            return null;
        }

        //7.若数据库中存在则更新redis,并设置过期时间（超时剔除）
        set(key, JSONUtil.toJsonStr(result), time, unit);

        //8.并返回商铺信息
        return result;
    }

    //创建线程池，便于缓存重建创建线程
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //查逻辑过期缓存
    public <R, ID> R queryWithLogicalExpare(String keyPrefix, String lockKeyPrefix, ID id, Long logicalExpare, Long lockTime, TimeUnit unit, TimeUnit lockUnit, Class<R> type, Function<ID, R> dbFallback) {
        //1.根据id从redis中查询缓存
        String key = keyPrefix + id;
        String redisDataJson = stringRedisTemplate.opsForValue().get(key);

        //2.如过未命中直接返回空
        if (StrUtil.isBlank(redisDataJson)) {
            return null;
        }

        //将缓存json反序列化为对象
        RedisData redisData = JSONUtil.toBean(redisDataJson, RedisData.class);
        R result = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();

        //4.如果命中判断缓存是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            //4.1如果缓存未过期直接返回
            return result;
        }

        //4.2如果缓存过期需要缓存重建
        String lockKey = lockKeyPrefix + id;
        //5.缓存重建获取互斥锁
        boolean flag = tryLock(lockKey, lockTime, lockUnit);

        //5.1获取失败则返回旧数据（佛系）
        if(!flag){
            return result;
        }

        //5.2获取成功

        //6.开启新线程重建缓存
        CACHE_REBUILD_EXECUTOR.submit(() -> {
            try {
                //6.1新线程查询数据库并更新缓存
                R dbResult = dbFallback.apply(id);
                setWithLogicalExpire(key, dbResult, logicalExpare, unit);

            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                //6.2新线程释放互斥锁
                unLock(lockKey);
            }
        });

        //6.3本线程返回旧数据
        return result;
    }

    //加锁
    private boolean tryLock(String key, Long time, TimeUnit unit) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", time, unit);
        return BooleanUtil.isTrue(flag);
    }

    //解锁
    private boolean unLock(String key) {
        Boolean flag = stringRedisTemplate.delete(key);
        return BooleanUtil.isTrue(flag);
    }
}
